package com.uduemc.biso.node.web.component.html;

import java.io.IOException;
import java.io.StringWriter;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.CollectionUtils;
import org.springframework.util.DigestUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.util.HtmlUtils;

import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.uduemc.biso.node.core.common.sysconfig.ArticleSysConfig;
import com.uduemc.biso.node.core.common.sysconfig.SysFontConfig;
import com.uduemc.biso.node.core.common.sysconfig.articlesysconfig.ArticleSysListConfig;
import com.uduemc.biso.node.core.common.sysconfig.articlesysconfig.ArticleSysListTextConfig;
import com.uduemc.biso.node.core.common.syspojo.ArticleDataList;
import com.uduemc.biso.node.core.common.udinpojo.PagingData;
import com.uduemc.biso.node.core.common.udinpojo.common.ImageConfig;
import com.uduemc.biso.node.core.entities.HRepertory;
import com.uduemc.biso.node.core.entities.SCategories;
import com.uduemc.biso.node.core.entities.SPage;
import com.uduemc.biso.node.core.entities.SRepertoryQuote;
import com.uduemc.biso.node.core.entities.SSystemItemCustomLink;
import com.uduemc.biso.node.core.entities.custom.Article;
import com.uduemc.biso.node.core.entities.custom.CategoryQuote;
import com.uduemc.biso.node.core.entities.custom.RepertoryQuote;
import com.uduemc.biso.node.core.utils.ComponentUtil;
import com.uduemc.biso.node.web.component.SiteUrlComponent;
import com.uduemc.biso.node.web.component.SpringContextUtils;
import com.uduemc.biso.node.web.component.html.common.HCPagingUdin;
import com.uduemc.biso.node.web.component.html.common.SystemListCrumbs;
import com.uduemc.biso.node.web.component.html.common.SystemListSearch;
import com.uduemc.biso.node.web.service.byfeign.SystemService;

import cn.hutool.core.util.StrUtil;

@Component
public class HSystemArticleItemListUdin {

	private static String name = "system_article_item_list";

	@Autowired
	private BasicUdin basicUdin;

	@Autowired
	private SiteUrlComponent siteUrlComponent;

	@Autowired
	private SystemListCrumbs systemListCrumbs;

	@Autowired
	private SystemListSearch systemListSearch;

	@Autowired
	private HCPagingUdin hCPagingUdin;

	public StringBuilder html(ArticleSysConfig articleSysConfig, SPage page, SCategories category, List<Article> listArticle, List<SCategories> listSCategories,
			String keyword, int pageNum, int total, int pageSize) throws JsonParseException, JsonMappingException, IOException {
		if (articleSysConfig == null || page == null) {
			return new StringBuilder("<!-- NLComp empty articleSysConfig -->\n");
		}
		ArticleSysListConfig articleSysListConfig = articleSysConfig.getList();
		ArticleSysListTextConfig articleSysListTextConfig = articleSysConfig.getLtext();
		String noData = HtmlUtils.htmlEscape(articleSysListTextConfig.findNoData());
		// 通过系统id 制作唯一编码
		String md5Id = DigestUtils.md5DigestAsHex(String.valueOf(page.getId()).getBytes());

		// 列表样式
		int listStyle = articleSysListConfig.findStyle();

		// 顶部class
		String topClass = "";
		int listStructure = articleSysListConfig.findStructure();
		if (listStructure == 2) {
			// 左右结构的时候
			topClass = "side_left";
		}

		// 制作面包屑
		// crumbs
		List<SCategories> list = new ArrayList<>();
		idList(list, listSCategories, category != null ? category.getId() : null);
		// 反转链表
		Collections.reverse(list);
		StringBuilder crumbs = crumbs(articleSysConfig, page, list);

		// 搜索
		// search
		StringBuilder search = search(articleSysConfig, keyword, md5Id);

		// 图片显示比例 $proportion
		String proportion = articleSysListConfig.findProportion();

		// 图片动画class $imgScaleClass
		String imgScaleClass = imgScaleClass(articleSysConfig);

		// 图片显示动画的html内容 $imgScaleHtml
		String imgScaleHtml = imgScaleHtml(articleSysConfig);

		// 分类打开方式
		String artcleCategoryTarget = getArtcleCategoryTarget(articleSysConfig);

		// 文章打开方式
		String artcleTarget = getArtcleTarget(articleSysConfig);

		// 是否显示时间
		int showDate = articleSysListConfig.findShowDate();

		// 是否显示简介
		int showSynopsis = articleSysListConfig.findShowSynopsis();

		// 是否显示分类
		int showCategory = articleSysListConfig.findShowCategory();

		// 文章列表部分
		// 标题是否加粗（已弃用）
		String titlebold = "";

		// articleDataList 数据链表
		List<ArticleDataList> dataList = getArticleDataList(page, listArticle);

		// 分页部分
		String listHref = siteUrlComponent.getListHref(page, category, "[page]", keyword);
		PagingData pagingData = articleSysListTextConfig.findPagingData();
		int pageTotal = (int) Math.ceil((double) total / (double) pageSize);
		// pagging
		StringBuilder pagging = hCPagingUdin.html(listHref, pageNum, pageTotal, pagingData);

		// 生成html渲染内容
		StringBuilder stringBuilder = new StringBuilder("<!-- NLComp -->\n");

		// 生成样式
		SysFontConfig titleStyle = articleSysConfig.getList().getTitleStyle();
		SysFontConfig synopsisStyle = articleSysConfig.getList().getSynopsisStyle();

		Map<String, Object> mapData = new HashMap<>();
		mapData.put("titleStyle", titleStyle);
		mapData.put("synopsisStyle", synopsisStyle);

		StringWriter render = basicUdin.render(name, "style", mapData);
		stringBuilder.append(render);

		mapData.put("topClass", topClass);
		mapData.put("crumbs", crumbs.toString());
		mapData.put("search", search.toString());
		mapData.put("noData", noData);
		mapData.put("showDate", showDate);
		mapData.put("showCategory", showCategory);
		mapData.put("showSynopsis", showSynopsis);
		// 列表配置相关
		mapData.put("titlebold", titlebold);
		mapData.put("proportion", proportion);
		mapData.put("imgScaleClass", imgScaleClass);
		mapData.put("imgScaleHtml", imgScaleHtml);
		mapData.put("artcleTarget", artcleTarget);
		mapData.put("artcleCategoryTarget", artcleCategoryTarget);
		// 列表数据
		mapData.put("dataList", dataList);
		mapData.put("pagging", pagging.toString());

		render = basicUdin.render(name, "default_" + listStyle, mapData);
		stringBuilder.append(render);

		return stringBuilder;
	}

	/**
	 * 获取 ArticleDataList 数据
	 * 
	 * @param page
	 * @param listArticle
	 * @return
	 */
	public List<ArticleDataList> getArticleDataList(SPage page, List<Article> listArticle) {
		SystemService systemServiceImpl = SpringContextUtils.getBean("systemServiceImpl", SystemService.class);
		List<ArticleDataList> dataList = new ArrayList<>();
		if (!CollectionUtils.isEmpty(listArticle)) {
			listArticle.forEach(item -> {
				ArticleDataList dataItem = new ArticleDataList();
				String title = HtmlUtils.htmlEscape(item.getSArticle().getTitle());
				String synopsis = item.getSArticle().getSynopsis() == null ? "" : HtmlUtils.htmlEscape(item.getSArticle().getSynopsis());
				SSystemItemCustomLink sSystemItemCustomLink = null;
				try {
					sSystemItemCustomLink = systemServiceImpl.findOkOneByHostSiteSystemItemId(item.getSArticle().getHostId(), item.getSArticle().getSiteId(),
							item.getSArticle().getSystemId(), item.getSArticle().getId());
				} catch (IOException e) {
				}
				
				String articleHref = siteUrlComponent.getArticleHref(page, item.getSArticle(), sSystemItemCustomLink);
				
				dataItem.setTitle(title).setSynopsis(synopsis).setHref(articleHref);

				// 分类
				CategoryQuote categoryQuote = item.getCategoryQuote();
				if (categoryQuote != null) {
					SCategories sCategories = categoryQuote.getSCategories();
					if (sCategories != null) {
						String categoryHref = siteUrlComponent.getCategoryHref(page, sCategories);
						dataItem.setCategoryName(HtmlUtils.htmlEscape(sCategories.getName())).setCategoryHref(categoryHref);
						if(sSystemItemCustomLink == null) {
							String articleHref2 = siteUrlComponent.getArticleHref(page, sCategories, item.getSArticle());
							dataItem.setHref(articleHref2);
						}
						
					}
				}

				// 图片
				RepertoryQuote repertoryQuote = item.getRepertoryQuote();
				if (repertoryQuote == null || repertoryQuote.getHRepertory() == null) {
					String src = siteUrlComponent.getImgEmptySrc();
					String imgTag = "<img alt=\"\" title=\"\" src=\"" + src + "\" />";
					dataItem.setImgTag(imgTag);
				} else {
					HRepertory hRepertory = repertoryQuote.getHRepertory();
					SRepertoryQuote sRepertoryQuote = repertoryQuote.getSRepertoryQuote();
					String src = siteUrlComponent.getImgEmptySrc();
					if (hRepertory != null) {
						src = siteUrlComponent.getImgSrc(hRepertory);
					}
					String iTitle = "";
					String iAlt = "";
					if (sRepertoryQuote != null) {
						String sRepertoryQuoteConfig = sRepertoryQuote.getConfig();
						if (StringUtils.hasText(sRepertoryQuoteConfig)) {
							ImageConfig imageConfig = ComponentUtil.getConfig(sRepertoryQuoteConfig, ImageConfig.class);
							String imageConfigTitle = imageConfig.getTitle();
							if (StringUtils.hasText(imageConfigTitle)) {
								iTitle = HtmlUtils.htmlEscape(imageConfigTitle);
							}
							String imageConfigAlt = imageConfig.getAlt();
							if (StringUtils.hasText(imageConfigAlt)) {
								iAlt = HtmlUtils.htmlEscape(imageConfigAlt);
							}
						}
					}

					String imgTag = "<img alt=\"" + iAlt + "\" title=\"" + iTitle + "\" src=\"" + src + "\" />";
					dataItem.setImgTag(imgTag);
				}

//				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
				DateTimeFormatter ofPattern = DateTimeFormatter.ofPattern("yyyy-MM-dd");
				DateTimeFormatter ofPatternNoDay = DateTimeFormatter.ofPattern("yyyy-MM");
				DateTimeFormatter ofPatternDay = DateTimeFormatter.ofPattern("dd");
				Date releasedAt = item.getSArticle().getReleasedAt();
				if (releasedAt != null) {
					Instant instant = releasedAt.toInstant();
					LocalDateTime ofInstant = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
					String format = ofInstant.format(ofPattern);
					// dateNoDay
					String formatNoDay = ofInstant.format(ofPatternNoDay);
					String formatDay = ofInstant.format(ofPatternDay);

					dataItem.setShowingTime(format).setDateNoDay(formatNoDay).setDateDay(formatDay);
				}
				dataList.add(dataItem);
			});
		}
		return dataList;
	}

	/**
	 * 制作搜索栏目
	 * 
	 * @param articleSysConfig
	 * @param keyword
	 * @param id
	 * @return
	 */
	protected StringBuilder search(ArticleSysConfig articleSysConfig, String keyword, String md5Id) {
		ArticleSysListConfig articleSysListConfig = articleSysConfig.getList();
		ArticleSysListTextConfig articleSysListTextConfig = articleSysConfig.getLtext();
		int listShowSearch = articleSysListConfig.findShowSearch();
		StringBuilder stringBuilder = new StringBuilder();
		if (listShowSearch == 0) {
			return stringBuilder;
		}
		String lanSearch = HtmlUtils.htmlEscape(articleSysListTextConfig.findLanSearch());
		String lanSearchInput = HtmlUtils.htmlEscape(articleSysListTextConfig.findLanSearchInput());
		String searchId = "search-" + md5Id;
		String inputId = "input-" + md5Id;
		if (StrUtil.isBlank(keyword)) {
			keyword = "";
		}

		stringBuilder = systemListSearch.render(searchId, inputId, lanSearch, lanSearchInput, keyword);
		return stringBuilder;
	}

	/**
	 * 制作面包屑
	 * 
	 * @param yourCurrentLocation
	 * @param page
	 * @param list
	 * @return
	 */
	protected StringBuilder crumbs(ArticleSysConfig articleSysConfig, SPage page, List<SCategories> list) {
//		ArticleSysListConfig articleSysListConfig = articleSysConfig.getList();
		ArticleSysListTextConfig articleSysListTextConfig = articleSysConfig.getLtext();
		ArticleSysListConfig listArticleSysListConfig = articleSysConfig.getList();
		int crumbslasttext = listArticleSysListConfig.getCrumbslasttext();

		String yourCurrentLocation = HtmlUtils.htmlEscape(articleSysListTextConfig.findYourCurrentLocation());
		StringBuilder stringBuilder = systemListCrumbs.render(yourCurrentLocation, crumbslasttext, page, list);
		return stringBuilder;
	}

	/**
	 * 通过 categoryId 以及递归的方式获取 listSCategories 数据中全部的父级数据，然後加入到 list 链表中
	 * 
	 * @param list
	 * @param listSCategories
	 * @param categoryId
	 */
	protected static void idList(List<SCategories> list, List<SCategories> listSCategories, Long categoryId) {
		if (categoryId == null || categoryId.longValue() < 1) {
			return;
		}
		for (SCategories sCategories : listSCategories) {
			if (categoryId.longValue() == sCategories.getId().longValue()) {
				list.add(sCategories);
				if (sCategories.getParentId() != null && sCategories.getParentId().longValue() > 0) {
					idList(list, listSCategories, sCategories.getParentId());
				}
				break;
			}
		}
	}

	// 图片动画class $imgScaleClass
	public static String imgScaleClass(ArticleSysConfig articleSysConfig) {
		ArticleSysListConfig articleSysListConfig = articleSysConfig.getList();
		int picAnimation = articleSysListConfig.findPicAnimation();
		switch (picAnimation) {
		case 1:
			return "news_imgScaleBig";
		case 2:
			return "news_imgTop";
		case 3:
			return "news_imgbgWhite";
		case 4:
			return "news_imgbgBlack";
		case 5:
			return "news_imgF";
		default:
			return "";
		}
	}

	// 图片显示动画的html内容 $imgScaleHtml
	public static String imgScaleHtml(ArticleSysConfig articleSysConfig) {
		ArticleSysListConfig articleSysListConfig = articleSysConfig.getList();
		int picAnimation = articleSysListConfig.findPicAnimation();
		switch (picAnimation) {
		case 3:
			return "<div class=\"imgbg\"></div>";
		case 4:
			return "<div class=\"imgbg\"></div>";
		default:
			return "";
		}
	}

	public static String getArtcleTarget(ArticleSysConfig articleSysConfig) {
		ArticleSysListConfig articleSysListConfig = articleSysConfig.getList();
		String listTarget = articleSysListConfig.findTarget();
		if (StringUtils.hasText(listTarget)) {
			return "target=\"" + listTarget + "\"";
		}
		return "";
	}

	public static String getArtcleCategoryTarget(ArticleSysConfig articleSysConfig) {
		ArticleSysListConfig articleSysListConfig = articleSysConfig.getList();
		String listCategoryTarget = articleSysListConfig.findCategoryTarget();
		if (StringUtils.hasText(listCategoryTarget)) {
			return "target=\"" + listCategoryTarget + "\"";
		}
		return "";
	}
}
